<?php

namespace app\common\controller;

use think\facade\Session;
use addons\user\model\UserMenu as UserMenuModel;
use addons\user\model\User as UserModel;
use think\helper\Str;

class AddonsUser extends Addons
{
    public function initialize()
    {
        parent::initialize();

        if (!Session::has('user')) {
            return $this->error('请先登录', (string)addons_url('user://login/index'));
        }

        $user = UserModel::find(Session::get('user.id'));
        if ($user['token'] != Session::get('user.token')) {
            return $this->error('当前账户已再其他地方登陆,请重新登陆', (string)addons_url('user://login/index'));
        }
        $this->user = $user;
        $this->assign('user', $user);
        $this->menu_info();
    }

    /**
     * 获取当前模块
     */
    private function menu_info()
    {
        $where = [
            'url' =>  $this->name . '://' . $this->controller . '/' . Str::snake($this->action),
        ];

        if (!$this->menu_info = UserMenuModel::where($where)->find()) {
            return $this->error('节点不存在');
        }
        if ($this->menu_info) {
            $this->menu_list();
            $this->assign('menu_info', $this->menu_info);
        }
    }

    /**
     * 左侧菜单
     */
    private function menu_list()
    {
        if ($this->request->isAjax() || $this->request->isPost()) {
            return;
        }
        $where = [
            ['is_show', '=', 1],
            ['status', '=', 1],
        ];

        $list = UserMenuModel::where($where)->order('sort desc')->select();
        $list->append(['optionss']);
        // dump($list->toArray());exit;
        $menu_list = children_menu($this->menu_info, $list->toArray());

        // dump($menu_list);exit;
        $this->assign('menu_list', $menu_list);

        //获取当前模块所有父级模块
        $menu_path = menu_path($list, $this->menu_info['pid']);
        $this->assign('menu_path', array_reverse($menu_path));
    }
}
